<template>
  <div class="user-accounts">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>用户账号管理</span>
          <el-button-group>
            <el-button type="primary" @click="handleBatchEnable"
              >批量启用</el-button
            >
            <el-button type="danger" @click="handleBatchDisable"
              >批量禁用</el-button
            >
            <el-button type="success" @click="exportData">导出数据</el-button>
          </el-button-group>
        </div>
      </template>

      <!-- 搜索栏 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="用户名">
          <el-input v-model="searchForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="searchForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="账号状态">
          <el-select v-model="searchForm.status" placeholder="请选择账号状态">
            <el-option label="正常" value="active" />
            <el-option label="已禁用" value="disabled" />
            <el-option label="待验证" value="pending" />
          </el-select>
        </el-form-item>
        <el-form-item label="注册时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="userList"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="用户ID" width="80" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="nickname" label="昵称" width="120" />
        <el-table-column prop="phone" label="手机号" width="120" />
        <el-table-column
          prop="email"
          label="邮箱"
          min-width="180"
          show-overflow-tooltip
        />
        <el-table-column prop="registerTime" label="注册时间" width="160" />
        <el-table-column prop="lastLoginTime" label="最后登录" width="160" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTag(row.status)">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button
                :type="row.status === 'active' ? 'danger' : 'success'"
                size="small"
                @click="handleToggleStatus(row)"
              >
                {{ row.status === "active" ? "禁用" : "启用" }}
              </el-button>
              <el-button type="primary" size="small" @click="handleEdit(row)">
                编辑
              </el-button>
              <el-button type="info" size="small" @click="viewDetail(row)">
                详情
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑用户信息" width="500px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" disabled />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="form.nickname" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="账号状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择账号状态">
            <el-option label="正常" value="active" />
            <el-option label="已禁用" value="disabled" />
            <el-option label="待验证" value="pending" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="用户详情" width="700px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="用户ID">{{
          currentUser.id
        }}</el-descriptions-item>
        <el-descriptions-item label="用户名">{{
          currentUser.username
        }}</el-descriptions-item>
        <el-descriptions-item label="昵称">{{
          currentUser.nickname
        }}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{
          currentUser.phone
        }}</el-descriptions-item>
        <el-descriptions-item label="邮箱">{{
          currentUser.email
        }}</el-descriptions-item>
        <el-descriptions-item label="账号状态">
          <el-tag :type="getStatusTag(currentUser.status)">
            {{ getStatusLabel(currentUser.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="注册时间">{{
          currentUser.registerTime
        }}</el-descriptions-item>
        <el-descriptions-item label="最后登录">{{
          currentUser.lastLoginTime
        }}</el-descriptions-item>
        <el-descriptions-item label="登录IP">{{
          currentUser.lastLoginIp
        }}</el-descriptions-item>
        <el-descriptions-item label="登录设备">{{
          currentUser.lastLoginDevice
        }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{
          currentUser.remark || "无"
        }}</el-descriptions-item>
      </el-descriptions>

      <div class="user-statistics mt-4">
        <h4>用户统计</h4>
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="stat-card">
              <div class="stat-title">订单总数</div>
              <div class="stat-value">{{ currentUser.orderCount || 0 }}</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="stat-card">
              <div class="stat-title">消费总额</div>
              <div class="stat-value">¥{{ currentUser.totalSpent || 0 }}</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="stat-card">
              <div class="stat-title">评价数</div>
              <div class="stat-value">{{ currentUser.reviewCount || 0 }}</div>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";

// 搜索表单
const searchForm = reactive({
  username: "",
  phone: "",
  status: "",
  dateRange: [],
});

// 表格数据
const loading = ref(false);
const userList = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const selectedUsers = ref([]);

// 编辑对话框
const editDialogVisible = ref(false);
const formRef = ref(null);
const form = reactive({
  username: "",
  nickname: "",
  phone: "",
  email: "",
  status: "",
  remark: "",
});

// 表单验证规则
const rules = {
  nickname: [{ required: true, message: "请输入昵称", trigger: "blur" }],
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" },
  ],
  status: [{ required: true, message: "请选择账号状态", trigger: "change" }],
};

// 详情对话框
const detailDialogVisible = ref(false);
const currentUser = ref({});

// 获取状态标签
const getStatusLabel = (status) => {
  const statuses = {
    active: "正常",
    disabled: "已禁用",
    pending: "待验证",
  };
  return statuses[status] || status;
};

// 获取状态标签样式
const getStatusTag = (status) => {
  const statuses = {
    active: "success",
    disabled: "danger",
    pending: "warning",
  };
  return statuses[status] || "";
};

// 搜索
const handleSearch = () => {
  // 实现搜索逻辑
};

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach((key) => {
    searchForm[key] = "";
  });
  handleSearch();
};

// 处理选择变化
const handleSelectionChange = (val) => {
  selectedUsers.value = val;
};

// 批量启用
const handleBatchEnable = () => {
  if (selectedUsers.value.length === 0) {
    ElMessage.warning("请选择要启用的用户");
    return;
  }
  // 实现批量启用逻辑
};

// 批量禁用
const handleBatchDisable = () => {
  if (selectedUsers.value.length === 0) {
    ElMessage.warning("请选择要禁用的用户");
    return;
  }
  // 实现批量禁用逻辑
};

// 导出数据
const exportData = () => {
  // 实现导出逻辑
};

// 切换用户状态
const handleToggleStatus = (row) => {
  const action = row.status === "active" ? "禁用" : "启用";
  ElMessageBox.confirm(`确认${action}该用户吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    try {
      // 实现状态切换逻辑
      ElMessage.success(`${action}成功`);
    } catch (error) {
      console.error(`${action}失败：`, error);
      ElMessage.error(`${action}失败`);
    }
  });
};

// 编辑用户
const handleEdit = (row) => {
  Object.assign(form, row);
  editDialogVisible.value = true;
};

// 查看详情
const viewDetail = (row) => {
  currentUser.value = row;
  detailDialogVisible.value = true;
};

// 提交表单
const submitForm = () => {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        // 实现提交表单的逻辑
        ElMessage.success("保存成功");
        editDialogVisible.value = false;
        handleSearch();
      } catch (error) {
        console.error("保存失败：", error);
        ElMessage.error("保存失败");
      }
    }
  });
};

// 分页相关方法
const handleSizeChange = (val) => {
  pageSize.value = val;
  handleSearch();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  handleSearch();
};

// 页面加载时获取数据
onMounted(() => {
  handleSearch();
});
</script>

<style scoped>
.user-accounts {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.mt-4 {
  margin-top: 20px;
}

.user-statistics {
  margin-top: 20px;
  border-top: 1px solid #eee;
  padding-top: 20px;
}

.stat-card {
  background-color: #f5f7fa;
  border-radius: 4px;
  padding: 15px;
  text-align: center;
}

.stat-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 24px;
  color: #303133;
  font-weight: bold;
}
</style>
